import React, { useCallback, useEffect } from 'react';
import { Button } from 'antd';

interface FullscreenButtonProps {
	containerRef: React.MutableRefObject<T | null>;
	isFullScreen: boolean;
	setIsFullScreen: (isFullScreen: boolean) => void;
}

const FullscreenButton: React.FC<FullscreenButtonProps> = ({ containerRef, isFullScreen, setIsFullScreen }) => {
	// 监听全屏变化
	useEffect(() => {
		const handleFullscreenChange = () => {
			const isDocumentFullscreen = !!(
				document.fullscreenElement ||
				document.webkitFullscreenElement ||
				document.mozFullScreenElement ||
				document.msFullscreenElement
			);
			setIsFullScreen(isDocumentFullscreen);
		};

		document.addEventListener('fullscreenchange', handleFullscreenChange);
		document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
		document.addEventListener('mozfullscreenchange', handleFullscreenChange);
		document.addEventListener('MSFullscreenChange', handleFullscreenChange);

		return () => {
			document.removeEventListener('fullscreenchange', handleFullscreenChange);
			document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
			document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
			document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
		};
	}, [setIsFullScreen]);

	const toggleFullscreen = useCallback(async () => {
		if (!containerRef.current) return;

		try {
			if (!isFullScreen) {
				if (containerRef.current.requestFullscreen) {
					await containerRef.current.requestFullscreen();
				} else if (containerRef.current.webkitRequestFullscreen) {
					await containerRef.current.webkitRequestFullscreen();
				}
			} else {
				if (document.exitFullscreen) {
					await document.exitFullscreen();
				} else if (document.webkitExitFullscreen) {
					await document.webkitExitFullscreen();
				}
			}
		} catch (err) {
			console.error('全屏切换失败:', err);
		}
	}, [isFullScreen, containerRef]);

	return (
		<div ref={containerRef}>
			<Button type="primary" onClick={toggleFullscreen} className="right-4 z-60 px-4 py-2">
				{isFullScreen ? '退出全屏' : '全屏'}
			</Button>
		</div>
	);
};

export default FullscreenButton;
